package models

import (
	"gorm.io/gorm"
)

type News struct {
	gorm.Model
	Title string `gorm:"type:varchar(30);not null;comment:'新闻标题'"`
	Time  string `gorm:"type:datetime;not null;comment:'发布时间'"`
	Types string `gorm:"type:varchar(30);not null;comment:'新闻分类'"`
}

func (n *News) Add() error {
	return DB.Create(&n).Error
}

func (n *News) Update() error {
	return DB.Updates(&n).Error
}

func (n *News) Del() error {
	return DB.Delete(&n).Error
}

func (n *News) GetNewBy() error {
	return DB.Where("title = ?", n.Title).Limit(1).Find(&n).Error
}

func (n *News) List(keyword string, page, pageSize int) (list []*News, err error) {
	db := DB.Debug()
	if keyword != "" {
		db = db.Where("title like ?", "%"+keyword+"%")
	}
	err = db.Scopes(Paginate(page, pageSize)).Find(&list).Error
	return
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
